<template>
  <div class="pd-20">
    <el-input v-model="searchCondition"
              placeholder="请输入仪器名称"
              clearable
              @clear="query"
              class="w-200" />
    <el-button type="primary"
               @click="query">查 询</el-button>
    <el-button type="primary"
               @click="edit(null)">新 增</el-button>

    <Table border
           stripe
           class="mt-20"
           :columns="titles"
           :data="dataList">
      <template slot-scope="{row, index}"
                slot="action">
        <span @click="edit(row)">编辑</span>
        <span @click="deleteData(row)">删除</span>
        <span @click="deviceManger(row)">设备管理</span>
      </template>
    </Table>
    <page @on-change="pageChange"
          :total="totals"
          ref="page"
          show-total></page>

    <el-dialog :visible.sync="dialogVisible"
               :title="title"
               width="30%"
               @close="dialogVisible = false"
               center
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="editData"
               label-position="right"
               label-width="120px"
               ref="formRefs"
               :rules="formRules">
        <el-form-item label="图标:"
                      prop="imageUrl">
          <el-upload class="avatar-uploader"
                     :action="fileUploadAction"
                     :show-file-list="false"
                     list-type="picture-card"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     :on-success="(response, file, fileList) =>uploadSuccess(response, file, fileList, 'imageUrl')"
                     :before-upload="file =>beforeUpload(file, 'imageUrl')">
            <img v-if="editData.imageUrl"
                 :src="editData.imageUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="仪器名称:"
                      prop="name">
          <el-input v-model="editData.name"
                    placeholder="请输入仪器名称"
                    type="text" />
        </el-form-item>
        <el-form-item label="仪器code:"
                      prop="code">
          <el-input v-model="editData.code"
                    placeholder="请输入仪器编码"
                    type="text" />
        </el-form-item>

        <el-form-item label="厂商:"
                      prop="factoryId">
          <el-select v-model="editData.factoryId"
                     placeholder="请选择请选择厂商"
                     filterable
                     remote
                     reserve-keyword
                     clearable
                     :remote-method="(query) => {remoteMethod(query, 'factory')}"
                     :loading="loading"
                     @change="val=>handleSelect(val, 'factory')">
            <el-option v-for="item in factoryFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型:"
                      prop="classifyId">
          <el-select v-model="editData.classifyId"
                     placeholder="请选择服务类型">
            <el-option v-for="item in classifyIdList"
                       :value="item.id"
                       :label="item.name"
                       :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号:"
                      prop="machineModel">
          <el-input v-model="editData.machineModel"
                    type="text"
                    placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="设备所有:"
                      prop="property">
          <el-select v-model="editData.property"
                     placeholder="请选择设备所有">
            <el-option v-for="item in propertyList"
                       :value="item.id"
                       :label="item.name"
                       :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定设备类型:"
                      prop="deviceBigType">
          <el-select v-model="editData.deviceBigType"
                     placeholder="请选择绑定设备类型">
            <el-option v-for="item in deviceBigTypes"
                       :value="item.id"
                       :label="item.name"
                       :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button type="plain"
                   @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm">确 定</el-button>
      </p>
    </el-dialog>
    <device-manger :device="deviceObj"
                   :visible.sync="isDevice"
                   v-if="isDevice">
    </device-manger>
    <el-dialog title="仪器图标"
               center
               :visible.sync="imageModal"
               width="30%">
      <img :src="imageUrl"
           style="width:100%;height:100%">
      <span slot="footer">
        <el-button type="primary"
                   @click="imageModal = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import deviceManger from './deviceManger';
  export default {
    name: "apparatusList",
    data () {
      return {
        imageModal: false,
        imageUrl: null,
        searchCondition: '',
        fileUploadAction: this.api.file.upload,
        currentPage: 1,
        totals: 0,
        pageSize: 10,
        dialogVisible: false,
        loading: false,
        editData: {
          id: null,
          code:'',
          name: "",
          factoryId: "",  // 厂商id
          factory: '', // 厂商名字
          machineModel: "",
          classifyId: "",
          imageUrl: "",
          property: "",
          deviceBigType: ""
        },
        // 服务类型
        classifyIdList: [
          { id: 2, name: '设备' },
          { id: 3, name: '胎心' },
          { id: 4, name: '耗材' }
        ],
        // 设备所有
        propertyList: [
          { id: 1, name: '自有设备' },
          { id: 2, name: '三方设备' }
        ],
        // 绑定设备类型
        deviceBigTypes: [
          { id: 1, name: '手柄' },
          { id: 2, name: '胶体金' },
          { id: 3, name: '其他POCT' },
          { id: 0, name: '其他设备' }
        ],
        factoryList: [], // 厂商列表
        factoryFilterList: [],
        titles: [
          {
            title: '仪器图标',
            key: 'imageUrl',
            width: 200,
            render: (h, params) => {
              return h('div', [
                h('img', {
                  attrs: {
                    src: params.row.imageUrl
                  },
                  style: {
                    width: '60px',
                    height: '60px',
                    'border-radius': '50%'
                  },
                  on: {
                    click: (event) => {
                      this.showBigImage(params.row.imageUrl);
                    }
                  }
                }),
              ]);
            }
          },
          {
            title: '仪器名称',
            key: 'name'
          },
          {
            title: '厂商',
            key: 'factory'
          },
          {
            title: '型号',
            key: 'machineModel'
          },
          {
            title: '创建时间',
            key: 'createTime',
            render: (h, params) => {
              return h('span',
                this.commonFunction.timestampFormat(new Date(params.row.createTime), 'yyyy-MM-dd hh:mm:ss'));
            }
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            width: 200
          }
        ],
        dataList: [],
        deviceObj: {},
        isDevice: false,
        title: '新增检测仪器',
        formRules: {
          imageUrl: [{ required: true, message: '请上传机器图标', trigger: 'blur' }],
          name: [{ required: true, message: '请输入仪器名称', trigger: 'blur' }],
          code: [{ required: true, message: '请输入仪器编码', trigger: 'blur' }],
          factoryId: [{ required: true, message: '请选择请选择厂商', trigger: 'blur' }],
          classifyId: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
          machineModel: [{ required: true, message: '请输入型号', trigger: 'blur' }],
          property: [{ required: true, message: '请选择设备所有', trigger: 'change' }],
          deviceBigType: [{ required: true, message: '请选择绑定设备类型', trigger: 'change' }],
        },
      }

    },
    created () {
      this.initTableData();
    },
    methods: {
      showBigImage (url) {
        this.imageUrl = url;
        this.imageModal = true;
      },
      query () {
        this.currentPage = 1;
        this.initTableData();
      },
      initTableData () {
        let param = {
          name: this.searchCondition,
          pageSize: this.pageSize,
          pageIndex: this.currentPage - 1
        };
        this.post(this.api.apparatus.getApparatusList, param).then((res) => {
          if (res.data.code === '200') {
            this.dataList = res.data.object;
            this.totals = res.data.totalNum;
          }
        });
      },
      pageChange (page) {
        this.currentPage = page;
        this.initTableData();
      },
      // 远程搜索
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          if (query) {
            if (type === 'factory') {
              _this.loading = true; // 锁住
              this.post(this.api.factory.getFactoryList, {
                name: query,
                pageIndex: 0,
                pageSize: this.pageSize
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading = false;
                  _this.factoryList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading = false;
                _this.factoryFilterList = _this.factoryList.filter(item => item.name.indexOf(query) > -1);
              }, 200);
            }
          } else {
            if (type === 'factory') {
              this.factoryFilterList = [];
            }
          }
        }
      },
      handleSelect (item, type) {
        if (type === 'factory') {
          this.editData.factoryId = item;
          let obj = this.factoryFilterList.find(el => el.id === item);
          this.editData.factory = obj.name;
        }
      },

      uploadSuccess (response, file, fileList, option) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          if (option === 'imageUrl') {
            this.$set(this.editData,'imageUrl',file.response.object[0])
            // this.editData.imageUrl = file.response.object[0];
            this.$message.success("上传成功");
          }
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        }
      },
      // 上传前的方法
      beforeUpload (file, option) {
        let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
        const isJPG = types.includes(file.type);
        if (option === 'imageUrl') {
          if (!isJPG) {
            this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
            return isJPG;
          }
          const isLt2M = file.size / 1024 / 1024 < 100;
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 100MB!');
            return isLt2M;
          }
        }
      },

      deleteData (row) {
        this.$confirm('您确定删除该条数据吗？')
          .then(_ => {
            this.post(this.api.apparatus.deleteApparatus, { "id": row.id }).then((res) => {
              if (res.data.code === '200') {
                this.$message.success("删除成功");
                this.initTableData();
              }
            });
          })
          .catch(_ => { });

      },
      // 设备管理
      deviceManger (row) {
        this.isDevice = true;
        this.deviceObj = row;
      },
      // 编辑
      edit (row) {
        this.dialogVisible = true;
        if (row) {
          this.title = '编辑检测仪器';
          this.post(this.api.apparatus.getApparatusDetail, { "id": row.id }).then((res) => {
            if (res.data.code === '200') {
              let resData = res.data.object
              this.editData = resData;
              this.factoryFilterList = [{ id: resData.factoryId, name: resData.factory }];
            }
          });
        } else {
          this.title = '新增检测仪器';

          this.$nextTick(() => {
            this.$refs['formRefs'].resetFields();
          })
          this.editData.id=null
        }
      },
      // 保存
      submitForm () {
        this.$refs['formRefs'].validate((valid) => {
          if (valid) {
            this.post(this.api.apparatus.updateApparatus, this.editData).then((res) => {
              if (res.data.code === '200') {
                this.$message.success("保存成功");
                this.dialogVisible = false;
                this.initTableData();
              }
            });
          }
        })
      },
    },
    components: {
      'device-manger': deviceManger
    }
  }
</script>

<style scoped lang="scss">
  .avatar-uploader {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    /deep/ .el-upload {
      .avatar {
        display: block;
        width: 98px;
        height: 98px;
      }
      &.el-upload--picture-card {
        width: 98px;
        height: 98px;
        line-height: 98px;
        overflow: hidden;
      }
      &:hover {
        border-color: #409eff;
      }
    }
    /deep/ .el-upload-list--picture-card {
      .el-upload-list__item {
        width: 98px;
        height: 98px;
      }
    }
  }
</style>
